//
//  DriverVehicleListViewController.m
//  阿帕
//
//  Created 阿帕 on 2019/12/25.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "DriverVehicleListViewController.h"
#import "VehicleManageCell.h"
#import "VechicleQrCodeViewController.h"
#import "AddVehicleVC.h"
#import "DriverVehicleManagementCell.h"
#import "DriverVehicleModel.h"
#import "CarAuthenticationController.h"

@interface DriverVehicleListViewController ()<UITableViewDelegate, UITableViewDataSource, DriverVehicleManagementCellDelegate>

@property (strong , nonatomic)UITextField *textFiled;

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray<DriverVehicleModel *> *dataArray;

@property (strong , nonatomic)UIView *noDataView;

@property (strong , nonatomic)UIButton *confirmButton;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation DriverVehicleListViewController

static const CGFloat cellHeight = 135.5;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    [self baseViewSetup];
//    [self getVehicleListRequest];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadNewData];
}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DriverVehicleManagementCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DriverVehicleManagementCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataArray[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    if (_isCanBindVehicle == 1) {
        VehicleListModel *model = self.dataArray[indexPath.row];
        
        [DCSpeedy dc_SetUpAlterWithView:self Title:@"" Message:CJStringWithFormat(@"是否将%@与车辆%@绑定在一起吗？",_driverName,model.licenseNumber) Sure:^{
            
            NSDictionary *params = @{@"partyCode": _partyCode,
                                     @"vehicleCode": model.code,
                                     @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
            };
            
            [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], DRIVER_BINDVEHICLE) withParameter:params withVC:self netName:@"绑定车辆" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:@"绑定成功" onView:weakSelf.view];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } Cancel:^{
            
        }];
    }
    
}

#pragma mark - DriverVehicleManagementCellDelegate

- (void)cellClickDefaultWithModel:(DriverVehicleModel *)model {
    
    NSString *url = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], @"/driver/bindDefaultVehicle");
    
    NSDictionary *params = @{
        @"vehicleCode": model.code,
        @"partyCode": [UserDefaultUtil valueForKey:DriverPartyCode],
    };
    
    @weakify(self);
    [HTTPManager postNetworkRequest:url
                     withParameter:params
                            withVC:self
                           netName:@"设置默认车辆"
                           success:^(id response, NSString *msg) {
        @strongify(self);
        [XSInfoView showInfo:msg onView:self.view];
        
        for (DriverVehicleModel *vehicle in self.dataArray) {
            if ([vehicle.code isEqualToString:model.code]) {
                vehicle.vehicleCode = model.code;
            } else {
                vehicle.vehicleCode = @"";
            }
        }
        [self.tableView reloadData];
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)cellClickEditWithModel:(DriverVehicleModel *)model {
    if (model.authStatusExt == 3) {
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:@"审核成功的车辆不能编辑" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* action = [UIAlertAction actionWithTitle:@"知道啦" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
           
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        AddVehicleVC *vavc = [[AddVehicleVC alloc] init];
        vavc.code = model.code;
        vavc.addType = 1;
        vavc.isOnlyView = ![model.teamCode isEqualToString:[UserDefaultUtil valueForKey:DriverPartyCode]];
        [self.navigationController pushViewController:vavc animated:YES];
    }
}

- (void)cellClickDeleteWithModel:(DriverVehicleModel *)model {
    
    @weakify(self);
    [DCSpeedy dc_SetUpAlterWithView:self Title:@"删除提示" Message:[NSString stringWithFormat:@"%@\"%@\"%@", @"确定要删除车牌号:", model.licenseNumber, @"的车辆吗？"] Sure:^{
        @strongify(self);
        [self request_deleteCarWithModel:model];
    } Cancel:^{
        
    }];
}

#pragma mark -

- (void)request_deleteCarWithModel:(DriverVehicleModel *)model {
    
    NSString *url = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], @"/vehicle/del");
    @weakify(self);
    [HTTPManager jsonNetworkRequestWithMethod:@"DELETE"
                                    urlString:url
                                withParameter:@{@"code" : model.code}
                                       withVC:self
                                      netName:@"删除车辆"
                              success:^(id response, NSString *msg) {
        @strongify(self);
        [XSInfoView showInfo:msg onView:self.view];
        model.isDefault = YES;
        [self loadNewData];
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self getVehicleListRequest];
}

- (void)loadMoreData{
    _pageNum ++;
    [self getVehicleListRequest];
}

- (void)baseViewSetup {
    
    self.navigationItem.title = @"车辆管理";
    
    self.view.backgroundColor = CJColorHexString(#F1F1F1);
    
    UIView *topView = [UIView new];
    [self.view addSubview:topView];
    topView.frame = CGRectMake(0, 0, kScreenWidth, 54);
    topView.backgroundColor = [UIColor whiteColor];
    
    _textFiled = [[UITextField alloc] initWithFrame:CGRectMake(15, 11.5, ScreenW - 30, 31)];
    [topView addSubview:_textFiled];
    _textFiled.font = font(13);
    _textFiled.text = @"";
    _textFiled.backgroundColor = CJColorHexString(#F1F2F3);
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textFiled.keyboardType = UIKeyboardTypeDefault;
    _textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入车辆牌照号" attributes:@{NSForegroundColorAttributeName: CJColorHexString(#737F9D)}];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftViewMode = UITextFieldViewModeAlways;
    [_textFiled addSubview: leftView];
    
    CGFloat searchImageViewWidth = 15.5;
    CGFloat searchImageViewX = _textFiled.width - searchImageViewWidth - 10.5;
    UIImageView *searchImage = [[UIImageView alloc] initWithFrame:CGRectMake(searchImageViewX, 8, searchImageViewWidth, searchImageViewWidth)];
    [_textFiled addSubview:searchImage];

    searchImage.userInteractionEnabled = YES;
    searchImage.image = [UIImage imageNamed:@"司机-车辆管理-搜索"];
    _textFiled.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15.5, 15.5)];
    _textFiled.rightViewMode = UITextFieldViewModeAlways;
    
    
    UIButton *searchButton = [UIButton new];
    [topView addSubview:searchButton];
    searchButton.frame = CGRectMake(0, 0, 40, 40);
    searchButton.center = [searchImage.superview convertPoint:searchImage.center toView:self.view];
    [searchButton addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    searchButton.backgroundColor = [UIColor greenColor];
//    searchButton.alpha = 0.3;
        
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.confirmButton];
}

- (void)searchButtonClick {
    [_textFiled endEditing:YES];
    _pageNum = 1;
    [self getVehicleListRequest];
}

- (void)getVehicleListRequest {
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *pamars = @{
        @"licenseNumber": StringCheck(_textFiled.text),
        @"pageSize": @"20",
        @"pageNum": @(_pageNum),
    };
    
    NSString *url = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], @"/vehicle/bindList");
    
    @weakify(self);
    [HTTPManager jsonNetworkRequestWithMethod:@"GET"
                                    urlString:url
                                withParameter:pamars
                                       withVC:self
                                      netName:@"车辆列表"
                                      success:^(id response, NSString *msg) {
        @strongify(self);
        if ([response[@"records"] count] != 0) {
            
            [self.dataArray addObjectsFromArray:[DriverVehicleModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
            self.noDataView.hidden = YES;
            self.tableView.hidden = NO;
        } else {
            if (_pageNum == 1) {
                self.noDataView.hidden = NO;
                self.tableView.hidden = YES;
            }
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (void)confirmButtonClick {
//    AddVehicleVC *vavc = [[AddVehicleVC alloc] init];
//    vavc.addType = 0;
//    [self.navigationController pushViewController:vavc animated:YES];
    CarAuthenticationController *vc = [[CarAuthenticationController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - LazyLoad

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 51, ScreenW, ScreenH - NavHeight - 51 - 75);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = CJColorHexString(#F1F1F1);
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DriverVehicleManagementCell class]) bundle:nil] forCellReuseIdentifier:@"DriverVehicleManagementCell"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (UIView *)noDataView {
    if (!_noDataView) {
        UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        view.image = image(@"gcy_img_list_found");
        view.contentMode = UIViewContentModeScaleAspectFit;
        view.center = self.view.center;
        view.cy_centerY -= 70;
        [self.view addSubview:view];
        _noDataView = view;
    }
    
    return _noDataView;
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setTitle:@"新增车辆" forState:UIControlStateNormal];
        [_confirmButton setBackgroundColor:Theme_ColorValue];
        cut(_confirmButton, BTN_BORDER_RADIUS);
        [_confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _confirmButton.frame = CGRectMake(20, ScreenH - NavHeight - 65, ScreenW-40, 45);
    }
    return _confirmButton;
}

@end
